package com.oauth.google.client.ui.youtube;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.oauth.google.client.beans.youtube.GoogleYouTubeModel;
import com.oauth.google.client.beans.youtube.YouTubeVideo;

public class HomePanel extends Composite {

	private static HomePanelUiBinder uiBinder = GWT
			.create(HomePanelUiBinder.class);

	interface HomePanelUiBinder extends UiBinder<Widget, HomePanel> {
	}

	@UiField
	VerticalPanel videosPanel;

	public HomePanel() {
		initWidget(uiBinder.createAndBindUi(this));

	}

	private VerticalPanel getDocument(final YouTubeVideo pVideo) {
		// hPanel.add(new Image(pTweet.getUser().getProfileImageUrl()));
		VerticalPanel vPanel = new VerticalPanel();

		if (pVideo.getLink() != null) {
			Anchor anchor = new Anchor(pVideo.getTitle(), true);
			anchor.addClickHandler(new ClickHandler() {

				public void onClick(ClickEvent pEvent) {
					Window.open(pVideo.getLink(), pVideo.getTitle(), null);
				}

			});
			vPanel.add(anchor);
		} else {
			vPanel.add(new Label(pVideo.getTitle()
					+ " - This video is no longer available"));
		}
		vPanel.setSpacing(4);
		return vPanel;
	}

	public void setData(GoogleYouTubeModel pModel) {
		videosPanel.clear();
		if (pModel != null) {
			List<YouTubeVideo> videos = pModel.getVideos();
			if (videos != null && !videos.isEmpty()) {
				for (YouTubeVideo video : videos) {
					videosPanel.add(getDocument(video));
				}
				return;
			}
		}
		videosPanel.add(new HTML("<b>No videos available.</b>"));

	}

}
